package com.example.covid.controller;

import com.example.covid.Utils.Result;
import com.example.covid.pojo.User;
import com.example.covid.service.UserService;
import com.wf.captcha.utils.CaptchaUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/** @author KamenRider */
@Controller
public class UserController {
  @Resource private UserService userService;

  /**
   * 登录 账户判断
   * @return
   */
  @RequestMapping("/loginIf")
  @ResponseBody
  public Result loginIf(User user, @RequestParam("captcha") String captcha,HttpServletRequest request , HttpSession session) {
    //验证码的判断
    if (!CaptchaUtil.ver(captcha, request)) {
      // 清除session中的验证码 验证码错误刷新一个新的验证码
      //CaptchaUtil.clear(request);
      return Result.fail("验证码不正确");
    }
    User login = userService.login(user);
    if (login != null) {
      // 登录成功
      login.setUserPassWord(null);
      session.setAttribute("userInfo", login);
      return Result.success();
    }
    // 登陆失败
    return Result.fail("登录失败!");
  }
  ;

  /**
   * 登录页面
   * @return
   */
  @GetMapping("/login")
  public String login() {
    return "login";
  }

  /**
   * 主页
   * @return */
  @RequestMapping("/main")
  public String main() {
    return "main";
  }

  /**
   * 验证码
   * @param request
   * @param response
   * @throws Exception
   */
  @RequestMapping("/captcha")
  public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
    CaptchaUtil.out(request, response);
  }
}
